package cn.shop.cloud.ws;

import lombok.Getter;
import lombok.Setter;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @program: shop-parent
 * @ClassName WebSocketServer
 * @description:
 * @author: Mokio
 * @create: 2024−12-27 11:51
 * @Version 2024 2.2 ; jdk1.8.0_181
 **/
@Component
@ServerEndpoint("/{uuid}")
public class WebSocketServer {
    // 使用线程安全的 hashmap
    // 原因：线程安全、高并发、查找快、单键灵活
    public static ConcurrentHashMap<String,WebSocketServer> clients = new ConcurrentHashMap<>();

    //会话
    private Session session;


    public static ConcurrentHashMap<String, WebSocketServer> getClients() {
        return clients;
    }

    public static void setClients(ConcurrentHashMap<String, WebSocketServer> clients) {
        WebSocketServer.clients = clients;
    }

    public Session getSession() {
        return session;
    }

    public void setSession(Session session) {
        this.session = session;
    }

    /**
     *  浏览器和服务器建立连接的时候会调用这个方法
     * @param session
     * @param uuid
     */
    @OnOpen
    public void onOpen(Session session,@PathParam("uuid") String uuid){
        System.out.println("客户端"+uuid+"建立了连接....");
        this.session = session;
        clients.put(uuid,this);
    }

    /**
     * 做动作的时候执行它
     * @param msg
     * @param uuid
     */
    @OnMessage
    public void onMessage(String msg,@PathParam("uuid") String uuid){
        System.out.println("客户端"+uuid+"说了:"+msg);
    }

    /**
     *  关闭的时候执行它
     * @param uuid
     */
    @OnClose
    public void onClose(@PathParam("uuid") String uuid){

        System.out.println("客户端"+uuid+"被移除了...");
        clients.remove(uuid);//移除了

    }

    /**
     * 出错的时候执行它
     * @param throwable
     */
    @OnError
    public  void onError(Throwable throwable){
        throwable.printStackTrace();//打印信息
    }
}